<script setup>
import {defineProps, onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import moment from "moment";
import {createPatient, getPatient, updatePatient, deletePatient} from "@/api/eyeCare.js";
import {getUser} from "@/utils/auth.js";
import {showConfirmDialog, showFailToast, showSuccessToast} from "vant";
import {convertDate} from "@/utils/index.js";

const router = useRouter()
const props = defineProps({
  id: String,
})

const formRef = ref();
const formData = ref({
  name: "",
  birthday: moment().format("YYYY-MM-DD"),
  // sex: 1 -> 男, 2 -> 女, 0 -> 未知
  sex: 1,
  height: 0,
  school: "",
  attendDate: null,
  grade: 1,
  clazz: null
})
const showPicker = ref(false)
const pickerValue = ref(convertDate(new Date()));
const loading = ref(false)
let isEdit = false

const initData = () => {
  if (props.id) {
    isEdit = true
    getPatient(props.id).then(resp => {
      if (resp.code === 0) {
        formData.value = {
              name: "",
              birthday: moment().format("YYYY-MM-DD"),
              // sex: 1 -> 男, 2 -> 女, 0 -> 未知
              sex: 1,
              height: 0,
              school: "",
              attendDate: null,
              grade: 1,
              clazz: null,
              ...resp.data
        }
        pickerValue.value = convertDate(new Date(formData.value.birthday))
      }
    })
  } else {
    isEdit = false
  }
}

const onConfirm = ({selectedValues}) => {
  pickerValue.value = selectedValues;
  formData.value.birthday = selectedValues.join("-");
  showPicker.value = false;
};
const onPopup = function () {
  showPicker.value = true
}
const onFailed = function () {
  showFailToast("提交失败")
}
const handleSave = async () => {
  await formRef.value.validate();
  let param = {
    ...formData.value,
  }
  try {
    loading.value = true
    let resp
    if (isEdit) {
      param.id = props.id
      resp = await updatePatient(param)
    } else {
      const currentUser = await getUser()
      param.userId = currentUser.id
      resp = await createPatient(param)
    }
    if (resp.code === 0) {
      showSuccessToast({type: 'success', message: resp.message});
      router.back()
    } else {
      showFailToast({type: 'danger', message: resp.message});
    }
  } catch (error) {
    showFailToast({type: 'danger', message: error.response.data.message});
  } finally {
    loading.value = false
  }
}

const handleRemove = () => {
  showConfirmDialog({
    message: '是否删除该就诊人？',
  })
      .then(() => {
        deletePatient(props.id)
            .then(res => {
              if (res.code === 0) {
                showSuccessToast("删除成功")
                router.back()
              }
            })
            .catch(err => {
              showFailToast(err.message)
            })
      })
      .catch(() => {
      })
}

onMounted(() => {
  initData()
})
</script>

<template>
  <van-form ref="formRef" @failed="onFailed">
    <van-cell-group inset>
      <van-field
          label="姓名"
          v-model="formData.name"
          name="name"
          placeholder="请输入姓名"
          required
          :rules="[{ required: true, message: '请输入姓名' }]"
      />
      <van-field
          label="出生日期"
          v-model="formData.birthday"
          name="birthday"
          placeholder="请输入出生日期"
          @click="onPopup"
          is-link
          readonly
          required
      />
      <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
        <van-date-picker
            :model-value="pickerValue"
            @confirm="onConfirm"
            @cancel="showPicker = false"
            :min-date="new Date(1990, 0, 1)"
            :max-date="new Date()"
        />
      </van-popup>
      <van-field
          label="性别"
          name="sex"
          placeholder="请选择性别"
      >
        <template #input>
          <van-radio-group v-model="formData.sex" direction="horizontal">
            <van-radio :name="1">男</van-radio>
            <van-radio :name="2">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
          v-model="formData.height"
          label="身高(cm)"
          name="height"
          placeholder="请输入身高"
          type="number"
      >
      </van-field>
      <van-field
          v-model="formData.school"
          label="学校"
          name="school"
          placeholder="请输入学校"
      >
      </van-field>
      <van-field
          v-model="formData.attendDate"
          label="入学年份"
          name="attendDate"
          placeholder="请输入入学年份"
          type="number"
      >
      </van-field>
      <van-field
          v-model="formData.clazz"
          label="班别"
          name="attendDate"
          placeholder="请输入班别"
          type="number"
      >
      </van-field>
      <van-field
          label="学校等级"
          name="grade"
      >
        <template #input>
          <van-radio-group v-model="formData.grade" direction="horizontal">
            <van-radio :name="1">小学</van-radio>
            <van-radio :name="2">初中</van-radio>
            <van-radio :name="3">高中</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button :loading="loading" @click="handleSave" block type="primary" native-type="submit">
        提交
      </van-button>
      <van-button v-if="isEdit" @click="handleRemove" style="margin-top: 16px" block native-type="submit">
        删除
      </van-button>
    </div>
  </van-form>
</template>

<style scoped lang="scss">
.van-cell-group {
  margin-top: 16px;
}
</style>